<?php

namespace app\api\controller\v2;

use addons\litestore\model\Litestoregoodsspec;
use addons\litestore\model\Litestoreorderaddress;
use addons\litestore\model\Wxlitestoregoods;
use addons\wechat\library\Config as ConfigService;
use app\admin\model\litestore\Litestoregoods;
use app\admin\model\litestore\Litestoreordergoods;
use app\admin\model\Litestorecart;
use app\admin\model\Orderday;
use app\admin\model\Profitbuy;
use app\admin\model\Useraddress;
use app\admin\model\Useragentwechat;
use app\admin\model\Userrelation;
use app\admin\model\Usersales;
use app\admin\model\Userscore;
use app\admin\model\Usershopweixin;
use app\admin\model\Userweixin;
use app\api\service\LepayService;
use app\api\service\MessageService;
use app\api\service\Orderservice;
use app\api\service\ProfitService;
use app\common\controller\Api;
use addons\litestore\model\Litestoreorder;

use addons\third\model\Third;
use EasyWeChat\Factory;
use EasyWeChat\Factory as WXPAY_APP;

class Order extends Api
{
    protected $noNeedRight = ['*'];
    protected $noNeedLogin = ['callback', 'vipcallback','checkRecevierOrder'];

    public function _initialize()
    {
        parent::_initialize();
        $this->user_id = $this->auth->id;
        $this->model = new Litestoreorder;

    }

    public function checkRecevierOrder(){

        $litestoreOrderModel =new \app\admin\model\litestore\Litestoreorder();
        $list = $litestoreOrderModel->where('order_status','transit')->limit(100)->select();
        foreach ($list as $key=>$val){
            $day = (time()-$val['freight_time'])/86400;
            if($day>=7){
                $litestoreOrderModel->where('id',$val['id'])->update(['order_status'=>'done','receipt_time'=>time()]);
            }
        }

        $this->success("处理成功");


    }


    public function buyPay()
    {

        $goods = $this->request->param('goods');
        $type = $this->request->param('type');
        $from = $this->request->param('from');
        if(!$from){
            $from="user";
        }
        //$seller_id = $this->request->param('uid');
        $items = json_decode(htmlspecialchars_decode($goods), true);

        $user = $this->auth->getUser();
        $seller_id = $user['ref_uid'];

        $litestoregoodsspec = new Litestoregoodsspec();
        $userAddressModel = new Useraddress();
        $address = $userAddressModel->where('uid', $user['id'])->where('isdefault',1)->find();
        if (!$address) {
            $this->error('请添加收货地址');
        }
        if($from == 'shop'){
            $userWxModel = new Usershopweixin();
            $wx = $userWxModel->where('uid', $user['id'])->find();
        }else{
            $userWxModel = new Userweixin();
            $wx = $userWxModel->where('uid', $user['id'])->find();
        }


        $goodModel = new Litestoregoods();
        $good = $goodModel->where('goods_id', $items[0]['goods_id'])->find();
        $spec_sku_ids = [];
        $totalAmount = 0;
        $totalScore = 0;
        foreach ($items as $key=>$val){
            $goods = $litestoregoodsspec->where('goods_id',$val['goods_id'])->where('spec_sku_id',$val['skuId'] )->find();
            $totalPrice = bcmul($goods['goods_price'], $val['count'], 2);
            $items[$key]['totalPrice'] = $totalPrice;
            $totalAmount = $totalAmount+$totalPrice;
            $totalScore += $val['score'];
        }
        $orderNo = getOrderSn();
        $data = array();
        $data['desc'] = $good['goods_name'];
        $data['openid'] = $wx['openid'];
        $data['orderNo'] = $orderNo;
        $data['amount'] =$totalAmount;
        $ratio = 100;
        if ($good['category_id'] == 12) {
            //加盟的产品
            $data['pay_price'] = $totalAmount*100;
            $data['callback_url'] = 'https://' . $_SERVER['HTTP_HOST'] . "/api/v1/order/vipcallback";
        } else {
            $group_id = $user['group_id'];
            if ($group_id == 2) {
                $ratio = $good['oneRatio'];
                $data['pay_price'] = $totalAmount * $ratio;
            } else if ($group_id == 3) {
                $ratio = $good['twoRatio'];
                $data['pay_price'] = $totalAmount * $ratio;
            } else if ($group_id == 4) {
                $ratio = $good['threeRatio'];
                $data['pay_price'] = $totalAmount * $ratio;
            } else {
                $data['pay_price'] = $totalAmount * 100;
            }
            $data['pay_price'] =intval( $data['pay_price']);
            $data['callback_url'] = 'https://' . $_SERVER['HTTP_HOST'] . "/api/v2/order/callback";
        }

        if($type == 1){
            if($from == 'shop'){
                $payService = new LepayService("3026016914", "");
                error_log("====shop pay===".json_encode($data));
                $ret = $payService->pay3($data);
            }else{
                $payService = new LepayService("3419916772", "");
                $ret = $payService->pay2($data);

            }

            error_log("====ret===" . json_encode($ret));
            if ($ret['resp_code'] == 0) {


                $data['goods'] = $items;
                $data['address'] = $address;
                $data['seller_id'] = $seller_id;
                $data['ratio'] = $ratio;
                $liteorder = new \app\admin\model\litestore\Litestoreorder();
                $id = $liteorder->addOrder($user['id'], $data);
                if ($id) {

                    $litestoreCartModel = new Litestorecart();
                    foreach ($items as $key=>$val){
                        $litestoreCartModel->where('goods_id',$val['goods_id'])->where('spec_sku_id',$val['skuId'])->delete();
                    }
                    $info = array();
                    $info['orderNo'] = $orderNo;
                    $info['payInfo'] = json_decode($ret['jspay_info'], true);
                    $this->success('下单成功', $info);
                } else {
                    $this->error("下单失败，请联系客服");
                }

            } else {
                $this->error("下单失败，请联系客服");
            }
        }else{

            $scoreModel = new Userscore();
            $score = $scoreModel->where('uid',$user['id'])->where('is_enable',1)->sum('score');
            if($score < $totalScore){
                $this->error('积分不足');
            }else{
                $data['goods'] = $items;
                $data['address'] = $address;
                $data['seller_id'] = $seller_id;
                $data['ratio'] = $ratio;
                $data['order_status'] = 'payed';

                $liteorder = new \app\admin\model\litestore\Litestoreorder();
                $id = $liteorder->addOrder($user['id'], $data);
                if ($id) {
                    $scoreModel->insert(['uid'=>$user['id'],'score'=>-$totalScore,'is_enable'=>1,'createtime'=>time(),'extra_id'=>$id,'extra_desc'=>$user['username']."积分兑换"]);
                }
                $info = array();
                $info['orderNo'] = $orderNo;
                $this->success('',$info);

            }

        }



    }

    public function callback()
    {

        $param = file_get_contents("php://input");
        error_log("======agent pay=====callback=================" . $param);

        $jsonxml = json_encode(simplexml_load_string($param, 'SimpleXMLElement', LIBXML_NOCDATA));
        $result = json_decode($jsonxml, true);
        $orderNo = $result['third_order_id'];
        $status = $result['status'];

        if ($status == 2) {
            $literOrder = new \app\admin\model\litestore\Litestoreorder();

            $order = $literOrder->where('order_no', $orderNo)->find();
            $literOrder->where('order_no', $orderNo)->update(['order_status' => 'payed',
                'pay_time' => time(), 'transaction_id' => $result['out_transaction_id']]);

            $startDate = date('Y-m-d',time());
            $startTime = strtotime($startDate." 00:00:00");
            $userDayOrderModel = new Orderday();
            $day = $userDayOrderModel->where('uid',$order['seller_id'])->where('createtime',$startTime)->find();
            if($day){
                $userDayOrderModel->where('createtime',$startTime)->where('uid',$order['seller_id'])->setInc('orderNum',1);
                $userDayOrderModel->where('createtime',$startTime)->where('uid',$order['seller_id'])->setInc('orderAmount',$order['pay_price']);
            }else{
                $userDayOrderModel->insert(['uid'=>$order['seller_id'],'createtime'=>$startTime,'orderNum'=>1,'orderAmount'=>$order['pay_price']]);
            }
            $monthDate = date('Y-m',time());
            $startMonth = strtotime($monthDate."-01 00:00:00");
            error_log("=======ddd=======");
            $userSalesModel = new Usersales();
            $userRelationModel = new Userrelation();
            $uid = $order['user_id'];

            $monthSales = $userSalesModel->where('createtime',$startMonth)->where('uid',$order['seller_id'])->find();
            error_log("====monthSales====".json_encode($monthSales));
            if($monthSales){
                $userSalesModel->where('id',$monthSales['id'])->setInc('month',$order['pay_price']);
                $userSalesModel->where('id',$monthSales['id'])->setInc('all',$order['pay_price']);
            }else{
                $lastMonth = $userSalesModel->where('uid',$order['seller_id'])->order('createtime','desc')->find();
                error_log("====lastmonth=====".json_encode($lastMonth));
                $month = 0;
                $all = 0;
                $teamMonth = 0;
                $teamAll= 0;
                if($lastMonth){
                    $month = 0;
                    $all = $lastMonth['all']+$order['pay_price'];
                    $teamMonth  = 0;
                    $teamAll = $lastMonth['teamAll'];
                }
                $userSalesModel->insert(['uid'=>$order['seller_id'],'month'=>$month,'all'=>$all,'teamMonth'=>$teamMonth,'teamAll'=>$teamAll,'createtime'=>$startMonth]);
            }

            $relation = $userRelationModel->where('uid',$uid)->find();
            $ids = explode(",",$relation['relation']);

            $where = ['uid' => ['in', $ids]];



            error_log("==order callback=startMonth====".$startMonth);

            $idList = $userSalesModel->field('uid')->where($where)->where('createtime',  $startMonth)->select();
            error_log("==order callback=idList====".json_encode($idList));

            $list = [];
            foreach ($idList as $key => $val) {
                $list[] = $val['uid'];
            }
            $ids = array_diff($ids, $list);

            error_log("==order callback=ids====".json_encode($ids));
            $insertData = [];
            foreach ($ids as $val) { //更新用户数据

                $ndata['uid'] = $val;
                $ndata['month'] = 0;
                $ndata['all'] = 0;
                $ndata['teamAll'] = 0;
                $ndata['teamMonth'] = 0;
                $ndata['createtime'] = $startMonth;
                $insertData[] = $ndata;

            }
            $userSalesModel->insertAll($insertData);
            //团队用户交易额
            $userSalesModel->where($where)->where('createtime',  $startMonth)->setInc('teamMonth', $order['pay_price']);
            $userSalesModel->where($where)->where('createtime',  $startMonth)->setInc('teamAll', $order['pay_price']);

        }
        echo "000000";
        $orderService = new Orderservice();
        $orderService->cacOrderAward($order);

    }


    public function vipcallback()
    {



        $param = file_get_contents("php://input");

        $jsonxml = json_encode(simplexml_load_string($param, 'SimpleXMLElement', LIBXML_NOCDATA));
        $result = json_decode($jsonxml, true);
//        error_log("========1====" . json_encode($result));
        $orderNo = $result['third_order_id'];
        $status = $result['status'];
        error_log("=========vipcallback==============" . $orderNo);

        error_log("=========vipcallback==============" . $status);

        if ($status == 2) {
            $literOrder = new \app\admin\model\litestore\Litestoreorder();
            $order = $literOrder->where('order_no', $orderNo)->find();
            error_log("=========vipcallback==============" . json_encode($order));

            if ($order['pay_price'] * 100 == $result['amount']) {
                $literOrder->where('order_no', $orderNo)->update(['order_status' => 'payed',
                    'pay_time' => time(), 'transaction_id' => $result['out_transaction_id']]);
            }

            $userModel = new \app\admin\model\User();
            $user = $userModel->where('id', $order['user_id'])->find();
            if ($user['group_id'] == 1) {
                $userModel->where('id', $order['user_id'])->update(['group_id' => 2]);
            }
            echo "000000";
            $orderService = new Orderservice();
            $orderService->cacRefAward($order);

        }


    }

    public function Get_order_num()
    {
        $NoPayNum = $this->model->where(['user_id' => $this->user_id, 'pay_status' => '10', 'freight_status' => '10', 'order_status' => '10', 'receipt_status' => '10'])->count();
        $NoFreightNum = $this->model->where(['user_id' => $this->user_id, 'pay_status' => '20', 'freight_status' => '10', 'order_status' => '10', 'receipt_status' => '10'])->count();
        $NoReceiptNum = $this->model->where(['user_id' => $this->user_id, 'pay_status' => '20', 'freight_status' => '20', 'order_status' => '10', 'receipt_status' => '10'])->count();
        return $this->success('', ['NoPayNum' => $NoPayNum, 'NoFreightNum' => $NoFreightNum, 'NoReceiptNum' => $NoReceiptNum]);
    }

    public function my()
    {
        $list = $this->model->getList($this->user_id);
        return $this->success('', $list);
    }

    public function detail()
    {
        $orderNo = $this->request->param('orderNo');


        $liteorderModel = new \app\admin\model\litestore\Litestoreorder();
        $order = $liteorderModel->where('order_no', $orderNo)->find();
        $order['orderTime'] = date('Y-m-d h:i:s', $order['createtime']);
        if (!$order) {
            $this->error('订单不存在');
        }
        $order_id = $order['id'];
        $litestoreordergoods = new \addons\litestore\model\Litestoreordergoods();
        $goods = $litestoreordergoods->where('order_id', $order_id)->select();
        $order['goods'] = $goods;
        $litestoreorderaddress = new Litestoreorderaddress();
        $address = $litestoreorderaddress->where('order_id', $order_id)->find();
        $order['address'] = $address;

        $goodsList = [];
        foreach ($order['goods'] as $index => $item) {
            $item['image'] = cdnurl(explode(",", $item['images'])[0], true);
            $item['sku_image'] = $item['spec']['spec_image'] == '' ? '' : cdnurl($item['spec']['spec_image'], true);
            $goodsList[] = $item;
        }
        $order['goods'] = $goodsList;
        return $this->success('', $order);
    }


    public function cart_pay()
    {
        $order = $this->model->getCart($this->user_id);

        // 创建订单
        if ($this->model->order_add($this->user_id, $order)) {
            // 清空购物车
            $this->model->CarclearAll($this->user_id);

            // 发起微信支付
            if ($this->request->request('type') && $this->request->request('type') == 'gzh') {
                $this->init_wx_pay_for_gzh(true);
                $this->make_wx_pay('wechat');
            } else {
                $this->init_wx_pay_for_wxapp();
                $this->make_wx_pay('wxapp');
            }
        }
        $this->error($this->model->getError() ?: '订单创建失败');
    }

    public function finish()
    {
        $id = $this->request->post("id");
        $order = $this->model;
        if ($order->finish($this->user_id, $id)) {
            return $this->success('');
        }
        return $this->error($order->getError());
    }

    public function cancel()
    {
        $id = $this->request->post("id");
        $order = $this->model->getOrderDetail($id, $this->user_id);

        if ($order->cancel($this->user_id, $id)) {
            return $this->success('');
        }
        return $this->error($order->getError());
    }

    public function order_pay()
    {
        $id = $this->request->post("id");
        $order = $this->model->getOrderDetail($id, $this->user_id);
        if (!$order->checkGoodsStatusFromOrder($order['goods'])) {
            return $this->error($order->getError());
        }
        $this->model = $order;
        // 发起微信支付
        if ($this->request->post('type') && $this->request->post('type') == 'gzh') {
            $this->init_wx_pay_for_gzh(true);
            $this->make_wx_pay('wechat');
        } else {
            $this->init_wx_pay_for_wxapp();
            $this->make_wx_pay('wxapp');
        }
    }

    public function getList()
    {

        $user = $this->auth->getUser();

        $status = $this->request->param('status');
        $where = [];
        $where['user_id'] = $user['id'];
        if ($status == '-1') {
            //全部
            $where['order_status'] = array('<>', 'paying');
        } else if ($status == '1') {
            //待发货
            $where['order_status'] = 'payed';
        } else if ($status == '2') {
            //待收货
            $where['order_status'] = 'transit';
        }
        $liteorderModel = new \app\admin\model\litestore\Litestoreorder();

        $list = $liteorderModel->with(['goods'])
            ->where($where)
            ->order(['createtime' => 'desc'])->limit(50)
            ->select();

        foreach ($list as $key => $val) {
            $good = $val['goods'];
            foreach ($good as $k => $v) {
                $image = cdnurl(explode(",", $v['images'])[0], true);
                $good[$k]['image'] = $image;
            }
        }




        $this->success('', $list);
    }


}
